package cn.com.jpushdemo;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.jeremy.arad.Arad;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

import cn.com.gridinfo.sooc.LoadingActivity;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.home.activity.HomeActivity;
import cn.com.gridinfo.sooc.core.my.msg.bean.PushNotice;
import cn.com.gridinfo.sooc.core.my.msg.dao.NoticeDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";

	//推送 sdk 收到消息
	@Override
	public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
		Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
		
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
                        
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
//        	processCustomMessage(context, bundle);

        
        }
		//收到通知
		else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			/**
			 * 将通知存入本地数据库
			 */
			PushNotice notice = new PushNotice();
			notice.setNoticeDec(bundle.getString(JPushInterface.EXTRA_ALERT));// 设置通知显示描述内容
			notice.setNoticeTitle(bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE));//设置通知标题
			notice.setSuid(Arad.preferences.getString(LocalMark.SERVER_ID.getName().toString())+"_"
					+Arad.preferences.getString(LocalMark.USER_UID.getName().toString()));
			notice.setCreateTime(new Date(System.currentTimeMillis()));
			JSONObject josn = null;
			try {
				josn  = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
				notice.setNoticeId(josn.getInt("news_id"));//设置服务器通知 id
				notice.setNoticeUrl("/index.php/wap/Public/msgshow/newsid/" +josn.getInt("news_id")+".html");//设置 url

			} catch (JSONException e) {
				e.printStackTrace();
				try {
					notice.setNoticeId(Integer.parseInt(josn.getString("news_id")));//设置服务器通知 id
					notice.setNoticeUrl("/index.php/wap/Public/msgshow/newsid/" +Integer.parseInt(josn.getString("news_id"))+".html");//设置 url
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
			}
			//存入 Android 通知数据库 状态初始化是未读 时间初始化当前时间
			NoticeDao noticeDao = new NoticeDao();
			noticeDao.saveNotice(notice);
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知---存入数据库--通知ID:"+notice.getNoticeId()+"--标题:"+notice.getNoticeTitle());
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
        	
        }
		//点击通知栏进入应用
		else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知"+bundle.toString());
			//Log.d(TAG, "[MyReceiver] 用户点击打开了通知 额外参数 url: "+bundle.getString(JPushInterface.EXTRA_EXTRA));
        	//打开自定义的Activity

			//判断应用是否在运行
			ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
			List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
			boolean isAppRunning = false;
			String MY_PKG_NAME = "cn.com.gridinfo.sooc";
			for (ActivityManager.RunningTaskInfo info : list) {
				if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
					isAppRunning = true;
					Log.i(TAG,info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
					break;
				}
			}
			Log.i("应用是否打开:>>>>>>>>>>>>>>>",""+isAppRunning);
			//如果应用打开
			if(isAppRunning) {
				//如果是自动登陆,表明已经登陆,直接打开消息公告列表界面
				if (Arad.preferences.getBoolean(LocalMark.IS_AUTO_LOGIN.getName())) {

					Intent i = new Intent(context, HomeActivity.class);
					i.putExtra("isPushNotice", true);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
					context.startActivity(i);

				}
				//应用打开在登陆界面或者瘦课网界面,提示登陆查看通知
				else{
					MessageUtils.showShortToast(context, "请登录后进入我的消息,查看消息公告");
				}

			}
//			应用没打开,打开应用
			else{
				//从 loading 加载开始,正常登陆,如果是自动登陆的话,自动登陆跳转进入消息公告列表界面
				Intent i = new Intent(context, LoadingActivity.class);
				i.putExtra("isPushNotice", true);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
				context.startActivity(i);
			}

//			PreferencesService service = new PreferencesService(context);
//			Log.i("应用是否打开:>>>>>>>>>>>>>>>",""+isAppRunning);
//			//如果应用打开
//			if(isAppRunning) {
//				//如果是自动登陆,表明已经登陆,直接打开消息公告列表界面
//				if (service.getAutoLoginPreferences().get("auto")) {
//
//					Intent i = new Intent(context, SlidingActivity.class);
//					i.putExtra("isPushNotice", true);
//					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//					context.startActivity(i);
//
//				}
//				//应用打开在登陆界面或者瘦课网界面,提示登陆查看通知
//				else{
//					Toast.makeText(context,"请登录后进入我的消息,查看消息公告",Toast.LENGTH_LONG).show();
//				}
//
//			}
////			应用没打开,打开应用
//			else{
//				//从 loading 加载开始,正常登陆,如果是自动登陆的话,自动登陆跳转进入消息公告列表界面
//				Intent i = new Intent(context, LoadingActivity.class);
//				i.putExtra("isPushNotice", true);
//				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				context.startActivity(i);
//
//			}


        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
        	
        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
        	boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
        	Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
        } else {
        	Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			}else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} 
			else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}
	
	//send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle) {
//		if (MainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (null != extraJson && extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			context.sendBroadcast(msgIntent);
//		}
	}
}
